<template>
  <div class="app-container">
    <el-card>
      <div class="filter-container">
        <el-form :inline="true">
          <el-form-item label="订单ID">
            <el-input
              v-model="queryParams.id"
              placeholder="请输入订单ID"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户">
            <el-select
              v-model="queryParams.userId"
              placeholder="请选择用户"
              clearable
              style="width: 200px"
              @change="handleQuery"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="门店">
            <el-select
              v-model="queryParams.storeId"
              placeholder="请选择门店"
              clearable
              style="width: 200px"
              @change="handleQuery"
            >
              <el-option
                v-for="item in storeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="药品">
            <el-select
              v-model="queryParams.medicineId"
              placeholder="请选择药品"
              clearable
              style="width: 200px"
              @change="handleQuery"
            >
              <el-option
                v-for="item in medicineList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择订单状态"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain @click="handleAdd">新增订单</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="orderList">
        <el-table-column label="订单ID" prop="id" width="80" />
        <el-table-column label="用户" prop="userId" width="120">
          <template #default="scope">
            {{ getUserName(scope.row.userId) }}
          </template>
        </el-table-column>
        <el-table-column label="门店" prop="storeId" width="120">
          <template #default="scope">
            {{ getStoreName(scope.row.storeId) }}
          </template>
        </el-table-column>
        <el-table-column label="订单金额" width="120">
          <template #default="scope"> {{ (scope.row.totalAmount / 100).toFixed(2) }} 元 </template>
        </el-table-column>
        <el-table-column label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" width="100">
          <template #default="scope">
            {{ getPayTypeLabel(scope.row.payType) }}
          </template>
        </el-table-column>
        <el-table-column label="期望送达时间" prop="deliveryTime" width="180" />
        <el-table-column label="下单时间" prop="createTime" width="180" />
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="success" link @click="handleViewDetails(scope.row)"
              >查看明细</el-button
            >
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="orderFormRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="用户" prop="userId">
            <el-select v-model="form.userId" placeholder="请选择用户" style="width: 100%">
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="门店" prop="storeId">
            <el-select v-model="form.storeId" placeholder="请选择门店" style="width: 100%">
              <el-option
                v-for="item in storeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="药品" prop="medicineId">
            <el-select v-model="form.medicineId" placeholder="请选择药品" style="width: 100%">
              <el-option
                v-for="item in medicineList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="订单状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择订单状态" style="width: 100%">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="支付方式" prop="payType">
            <el-select v-model="form.payType" placeholder="请选择支付方式" style="width: 100%">
              <el-option
                v-for="dict in payTypeOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="期望送达时间" prop="deliveryTime">
            <el-date-picker
              v-model="form.deliveryTime"
              type="datetime"
              placeholder="选择期望送达时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 订单明细对话框 -->
      <el-dialog title="订单明细" v-model="detailsOpen" width="800px" append-to-body>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单ID">{{ currentOrder.id }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentOrder.userId }}</el-descriptions-item>
          <el-descriptions-item label="门店ID">{{ currentOrder.storeId }}</el-descriptions-item>
          <el-descriptions-item label="订单金额"
            >{{ (currentOrder.totalAmount / 100).toFixed(2) }} 元</el-descriptions-item
          >
          <el-descriptions-item label="订单状态">{{
            getStatusLabel(currentOrder.status)
          }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{
            getPayTypeLabel(currentOrder.payType)
          }}</el-descriptions-item>
          <el-descriptions-item label="期望送达时间">{{
            currentOrder.deliveryTime
          }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{
            currentOrder.createTime
          }}</el-descriptions-item>
        </el-descriptions>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="detailsOpen = false">关 闭</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listOrder, getOrder, addOrder, updateOrder, delOrder } from '@/api/order'
import { listUser } from '@/api/user'
import { listStore } from '@/api/store'
import { listMedicine } from '@/api/medicine'
// 遮罩层
const loading = ref(false)
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 是否显示明细弹出层
const detailsOpen = ref(false)
// 当前订单对象
const currentOrder = ref({})
// 查询参数
const queryParams = ref({
  id: undefined,
  storeId: undefined,
  status: undefined
})

// 表单参数
const form = ref({
  id: undefined,
  userId: undefined,
  storeId: undefined,
  totalAmount: 0,
  status: 0,
  payType: 0,
  deliveryTime: undefined,
  medicineId: undefined
})

// 表单校验
const rules = {
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  storeId: [{ required: true, message: '门店ID不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '订单状态不能为空', trigger: 'change' }],
  payType: [{ required: true, message: '支付方式不能为空', trigger: 'change' }],
  deliveryTime: [{ required: true, message: '期望送达时间不能为空', trigger: 'blur' }]
}

// 订单状态选项
const statusOptions = [
  { value: 0, label: '待付款' },
  { value: 1, label: '已付款' },
  { value: 2, label: '已发货' },
  { value: 3, label: '已送达' }
]

// 支付方式选项
const payTypeOptions = [
  { value: 0, label: '支付宝' },
  { value: 1, label: '微信' },
  { value: 2, label: '银行卡' }
]

const orderFormRef = ref()
const orderList = ref([])
const orderDetailsList = ref([])
const medicineList = ref([])

// 获取订单状态标签
const getStatusLabel = (status) => {
  const found = statusOptions.find((item) => item.value === status)
  return found ? found.label : status
}

// 获取支付方式标签
const getPayTypeLabel = (payType) => {
  const found = payTypeOptions.find((item) => item.value === payType)
  return found ? found.label : payType
}

// 获取订单状态标签类型
const statusTagType = (status) => {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'warning'
    case 2:
      return 'primary'
    case 3:
      return 'success'
    default:
      return 'info'
  }
}

// 获取药品名称
const getMedicineName = (medicineId) => {
  const medicine = medicineList.value.find((item) => item.id === medicineId)
  return medicine ? medicine.name : medicineId
}

/** 查询订单列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await listOrder(queryParams.value)
    orderList.value = res
    loading.value = false
  } catch (error) {
    loading.value = false
    console.error(error)
  }
}

/** 获取药品列表 */
const getMedicineList = async () => {
  try {
    const res = await listMedicine()
    medicineList.value = res
  } catch (error) {
    console.error(error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    id: undefined,
    storeId: undefined,
    status: undefined
  }
  handleQuery()
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加订单'
}

/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset()
  const id = row.id
  getOrder(id).then((response) => {
    Object.assign(form.value, response)
    open.value = true
    title.value = '修改订单'
  })
}

/** 查看明细按钮操作 */
const handleViewDetails = async (row) => {
  currentOrder.value = row
  detailsOpen.value = true
  try {
    // 查询订单明细
    const res = await listOrderdetail({ orderId: row.id })
    orderDetailsList.value = res
  } catch (error) {
    console.error(error)
  }
}

/** 提交按钮 */
const submitForm = () => {
  orderFormRef.value.validate((valid) => {
    if (valid) {
      if (form.value.id) {
        updateOrder(form.value).then((response) => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addOrder(form.value).then((response) => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
const handleDelete = (row) => {
  const id = row.id
  ElMessageBox.confirm('是否确认删除该订单?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(function () {
      return delOrder(id)
    })
    .then(() => {
      getList()
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

/** 表单重置 */
const reset = () => {
  form.value = {
    id: undefined,
    userId: undefined,
    storeId: undefined,
    totalAmount: 0,
    status: 0,
    payType: 0,
    deliveryTime: undefined
  }
}

/** 取消按钮 */
const cancel = () => {
  open.value = false
  reset()
}

onMounted(() => {
  getList()
  getMedicineList()
})

// 用户选项
const userOptions = ref([])
// 门店选项
const storeOptions = ref([])

// 获取用户列表
const getUserList = async () => {
  try {
    const res = await listUser()
    userOptions.value = res || []
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取门店列表
const getStoreList = async () => {
  try {
    const res = await listStore()
    storeOptions.value = res || []
  } catch (error) {
    console.error('获取门店列表失败', error)
    ElMessage.error('获取门店列表失败')
  }
}

// 组件挂载时获取用户和门店数据
onMounted(() => {
  getUserList()
  getStoreList()
  getList()
})

// 获取用户名称
const getUserName = (userId) => {
  const user = userOptions.value.find((item) => item.id === userId)
  return user ? user.username : userId
}

// 获取门店名称
const getStoreName = (storeId) => {
  const store = storeOptions.value.find((item) => item.id === storeId)
  return store ? store.name : storeId
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  padding-bottom: 10px;
}
.mb8 {
  margin-bottom: 8px;
}
.mt20 {
  margin-top: 20px;
}
</style>
